package com.lulalei.dbviewer.commons.utils;

import com.lulalei.dbviewer.commons.bean.JDBCConnectBean;
import com.lulalei.dbviewer.commons.cache.CacheManager;
import com.lulalei.dbviewer.commons.cache.CacheMap;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

/**
 * <p>
 * 保持数据库连接
 * </p>
 *
 * @author lulalei
 * @create 2021-05-27 19:27
 */
@Slf4j
@Component
public class KeepAliveUtils {

    @PostConstruct
    public void init() {
        //类加载时启动定时器
        keepConnect();
    }

    public static void keepConnect() {
        Timer timer = new Timer();
        timer.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                CacheMap jdbc = CacheManager.getCacheMap("jdbc");
                if (jdbc != null && jdbc.size() != 0) {
                    //在缓存中获取所有的jdbc对象，遍历进行维护
                    Map<String, Object> map = jdbc.getMap();
                    for (Map.Entry<String, Object> stringObjectEntry : map.entrySet()) {
                        JDBCConnectBean connection = (JDBCConnectBean) stringObjectEntry.getValue();
                        try {
                            Statement statement = connection.getConnection().createStatement();
                            statement.executeQuery("select 1 = 1");
                        } catch (SQLException throwables) {
                            throwables.printStackTrace();
                        }
                    }
                }
            }
        }, 60000, 60000);
    }
}
